/*
 * Copyright 2007 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import net.datajanitor.baja.data.BoxFile;
import net.datajanitor.baja.data.BoxFileInfo;
import net.datajanitor.baja.data.BoxFileInfoVisitor;
import net.datajanitor.baja.spi.FileTreeBuilder;

class BoxFileInfoImpl implements BoxFileInfo {
    private static final BoxFileInfoImpl ROOT_PARENT = newDirectory(null, null, FileTreeBuilder.ROOT_PARENT_DIR_ID, "ROOT_PARENT_DIR");
    private final int id;
    private final String name;
    private final boolean isDir;
    private final List<BoxFileInfoImpl> children;
    private final BoxConnection connection;
    private BoxFileInfoImpl parent;
    private boolean deleted;
    
    private BoxFileInfoImpl(BoxFileInfoImpl parent, BoxConnection connection, int id, String name, boolean isDir) {
        this.parent = parent;
        this.connection = connection;
        this.id = id;
        this.name = name;
        this.isDir = isDir;
        this.children = new ArrayList<BoxFileInfoImpl>();
    }
    
    static BoxFileInfoImpl newFile(BoxFileInfoImpl parent, BoxConnection connection, int id, String name) {
        return new BoxFileInfoImpl(parent, connection, id, name, false);    
    }
    
    static BoxFileInfoImpl newDirectory(BoxFileInfoImpl parent, BoxConnection connection, int id, String name) {
        if (parent == null) {
            parent = ROOT_PARENT;
        }
        return new BoxFileInfoImpl(parent, connection, id, name, true);    
    }
       
    void addChild(BoxFileInfoImpl child) {
        this.children.add(child);    
    }
    
    boolean removeChild(BoxFileInfoImpl child) {
        return this.children.remove(child);
    }
    
    List<BoxFileInfoImpl> getChildren() {
        return this.children;
    }
    
    void unlink() {
        this.accept(new BoxFileInfoVisitor() {
            public void visit(BoxFileInfo file) {
                BoxFileInfoImpl fileInfo = (BoxFileInfoImpl) file;
                fileInfo.parent.removeChild(fileInfo);
                fileInfo.parent = null;
                fileInfo.deleted = true;
            }
        });
    }

    public Iterator<BoxFileInfo> childIterator() {
        return new Iterator<BoxFileInfo>() {
            private int cur = 0;
            public boolean hasNext() {
                return this.cur < children.size();
            }

            public BoxFileInfo next() {
                if (hasNext()) {
                    return children.get(this.cur++);
                } else {
                    throw new NoSuchElementException("Error: attempted to read past the end of the childIterator");    
                }
            }

            public void remove() {
                throw new UnsupportedOperationException("Error: childIterator is read-only");
            }            
        };
    }

    public int getId() {
        return this.id;
    }

    public boolean isDirectory() {
        return this.isDir;
    }

    public boolean isFile() {
        return !isDirectory();
    }

    public String getName() {
        return this.name;
    }

    public BoxFile getParent() {
        return (isRoot()) ? null : this.parent;
    }

    public boolean isRoot() {
        return this.parent == ROOT_PARENT;
    }
    
    public boolean isDeleted() {
        return this.deleted;
    }
    
    public String getPath() {
        StringBuilder path = new StringBuilder();
        BoxFile parent = getParent();
        if (parent != null) {
            path.append(parent.getPath()).append(this.name);
        }
        
        if (this.isDir) {
            path.append("/");
        }
        
        return path.toString();
    }    
    
    public void accept(BoxFileInfoVisitor visitor) {
        visitor.visit(this);
        
        for (BoxFileInfoImpl child : new ArrayList<BoxFileInfoImpl>(this.children)) {
            child.accept(visitor);
        }
    }
    
    public void delete() {
        this.connection.delete(this);
    }

    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = PRIME * result + ((children == null) ? 0 : children.hashCode());
        result = PRIME * result + id;
        result = PRIME * result + (isDir ? 1231 : 1237);
        result = PRIME * result + ((name == null) ? 0 : name.hashCode());
        result = PRIME * result + ((parent == null) ? 0 : parent.getId());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final BoxFileInfoImpl other = (BoxFileInfoImpl) obj;
        if (children == null) {
            if (other.children != null)
                return false;
        } else if (!children.equals(other.children))
            return false;
        if (id != other.id)
            return false;
        if (isDir != other.isDir)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (parent == null) {
            if (other.parent != null)
                return false;
        } else if (!parent.equals(other.parent))
            return false;
        return true;
    }
    
    public String toString() {
        return getClass().getSimpleName() + "[id=" + getId() + ",name=" + getName() + ",isDir=" + isDirectory() + "]";
    }
}